package com.smarttiger.zero.admin.filter;


import com.smarttiger.zero.admin.util.Constant;
import com.smarttiger.zero.admin.util.ZEROCacheUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@Configuration
public class LoginFilter implements Filter {
    Log log = LogFactory.getLog("LoginFilter");

    @Bean
    public FilterRegistrationBean authFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new LoginFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue"); //
        registration.setName("authFilter");
        registration.setOrder(2);
        return registration;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURL().toString();
        boolean b = StringUtils.endsWithIgnoreCase(url, "users/login/query");
        boolean b2 = url.contains("/ZERO/");
        System.out.println("------999-------"+url);
        if (b || b2) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            String authorization = request.getHeader("Authorization");
            String s = ZEROCacheUtil.userSession.get(Constant.TOKEN);
            if (StringUtils.isEmpty(s) || !s.equals(authorization)) {
                servletResponse.getWriter().write("{\"auth\":\"no_authorization\"}");
            } else {
                ZEROCacheUtil.userSession.put(Constant.TOKEN, s);
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
